package com.sdruixinggroup.mondayb2b.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.API.Constants;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.AliPayBeen;
import com.sdruixinggroup.mondayb2b.models.ModelBeen;
import com.sdruixinggroup.mondayb2b.models.OrderInfor;
import com.sdruixinggroup.mondayb2b.models.UPPayBeen;
import com.sdruixinggroup.mondayb2b.models.WeiChatPayBeen;
import com.sdruixinggroup.mondayb2b.ui.Activities.AppraiseActivity;
import com.sdruixinggroup.mondayb2b.ui.Activities.CheckPayNongziActivity;
import com.sdruixinggroup.mondayb2b.ui.Activities.OffLineDetialActivity;
import com.sdruixinggroup.mondayb2b.utils.DisplayUtil;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.sdruixinggroup.mondayb2b.widget.OrderInforGoodView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.sdruixinggroup.mondayb2b.R.id.tv_status_2;

/**
 * Created by tangjie on 2017/11/12.
 */

public class OrderDetailActivity extends BaseActivity {

    @BindView(R.id.ib_back)
    ImageView ibBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_order_NO)
    TextView tvOrderNO;
    @BindView(R.id.tv_state)
    TextView tvState;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.iv_shop_header)
    ImageView ivShopHeader;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.ll_goods_content)
    LinearLayout llGoodsContent;
    @BindView(R.id.tv_pay_way)
    TextView tvPayWay;
    @BindView(R.id.tv_pay_time)
    TextView tvPayTime;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_status_1)
    TextView tvStatus1;
    @BindView(tv_status_2)
    TextView tvStatus2;
    @BindView(R.id.tv_coupon)
    TextView tvCoupon;
    @BindView(R.id.ll_bottom_bt)
    LinearLayout llBottomBt;
    private int id = 0;
    private int status;
   private  OrderInfor.OrderBean orderBean;
    private IWXAPI iwxapi;
    public static  OrderDetailActivity instance;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        instance=this;
        setContentView(R.layout.activity_detail);
        ButterKnife.bind(this);
        iwxapi = WXAPIFactory.createWXAPI(getApplicationContext(), Constants.APP_ID);
        // 将该app注册到微信
        iwxapi.registerApp(Constants.APP_ID);
        ibBack.setImageResource(R.mipmap.share_back);
        tvTitle.setText("订单详情");
        id = getIntent().getIntExtra("ID", 0);
        queryData(id);
        tvStatus1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (status) {
                    case 1:
                        remindOrder(id,7);
                        break;
                    case 2:
                        break;
                    case 3:
                        tvStatus1.setVisibility(View.INVISIBLE);
                        tvStatus2.setVisibility(View.VISIBLE);
                        break;
                    case 4:
                        tvStatus1.setVisibility(View.INVISIBLE);
                        tvStatus2.setText("确认收货");
                        tvStatus2.setVisibility(View.VISIBLE);
                        break;
                    case 5:
                        tvStatus1.setVisibility(View.INVISIBLE);
                        tvStatus2.setText("立即评价");
                        tvStatus2.setVisibility(View.VISIBLE);
                        break;
                    case 6:
                        tvStatus1.setText("删除订单");
                        remindOrder(id,6);
                        break;
                }
            }
        });

        tvStatus2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (status) {
                    case 1:
                        remindOrder(id,1);
                        break;
                    case 2:

                        break;
                    case 3:
                        remindOrder(id,3);
                        break;
                    case 4:
                        remindOrder(id,4);
                        break;
                    case 5:
                        Intent intent = new Intent(getBaseContext(), AppraiseActivity.class);
                        intent.putExtra("ID",id);
                        startActivity(intent);
                        break;
                    case 6:
                        tvStatus1.setVisibility(View.INVISIBLE);
                        tvStatus2.setText("删除订单");
                        remindOrder(id,6);
                        break;
                }


            }
        });

        tvPayWay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    if(null != orderBean){
                        if(orderBean.getPayment_type() == 5){
                            Intent intent =new Intent(getApplication(),OffLineDetialActivity.class);
                            intent.putExtra("object",orderBean);
                            startActivity(intent);
                        }else if(orderBean.getPayment_type() == 6){
                            Intent intent =new Intent(getApplication(),CheckPayNongziActivity.class);
                            intent.putExtra("object",orderBean);
                            startActivity(intent);
                        }

                    }
            }
        });
    }

    @OnClick(R.id.ib_back)
    public void onClick() {
        finish();
    }

    private void queryData(int id) {

        String url = API.ORDERS_DETIAL + id + "?" + "&access_token=" + UserInfoUtil.getInfoToken(this);
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");

        TypeToken<OrderInfor> typeToken = new TypeToken<OrderInfor>() {
        };

        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<OrderInfor>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(OrderInfor response, int id) {

                if (null != response) {
                    orderBean = response.getOrder();
                    tvOrderNO.setText("订单号：" + orderBean.getOrder_sn());
                    tvTime.setText("提交时间：" + orderBean.getCreated_time());
                    tvState.setText(orderBean.getStatus_name());
                    tvName.setText(orderBean.getAddress().getConsignee() + " " + orderBean.getAddress().getPhone());
                    tvAddress.setText(orderBean.getAddress().getProvince_name() + orderBean.getAddress().getCity_name() + orderBean.getAddress().getCounty_name() + orderBean.getAddress().getStreet());
                    if (llGoodsContent.getChildCount() > 0) {
                        llGoodsContent.removeAllViews();
                    }

                    Glide.with(OrderDetailActivity.this).load(orderBean.getMerchant().getThumb()).error(R.drawable.shipping_shop).into(ivShopHeader);
                    tvShopName.setText(orderBean.getMerchant().getName());
                    List<OrderInfor.OrderBean.OrderGoodsBean> orderGoodsBeen = orderBean.getOrder_goods();
                    for (OrderInfor.OrderBean.OrderGoodsBean orderGoodsBean : orderGoodsBeen) {
                        OrderInforGoodView orderInforGoodView = new OrderInforGoodView(OrderDetailActivity.this);
                        orderInforGoodView.setData(orderGoodsBean,OrderDetailActivity.this.id,orderBean.getStatus());
                        llGoodsContent.addView(orderInforGoodView);
                    }
                    tvPayWay.setText("支付方式: " + orderBean.getPayment_type_name());
                    // 状态：-2已关闭 -1已驳回 1待付款 2待审核 3待发货 4待收货 5待评价 6已完成 ,
                    llBottomBt.setVisibility(View.VISIBLE);
                    status = orderBean.getStatus();
                    tvPayTime.setVisibility(View.GONE);
                    line.setVisibility(View.GONE);
                    tvStatus2.setTextColor(getResources().getColor(R.color.white));
                    switch (status) {
                        case -1:
                            llBottomBt.setVisibility(View.GONE);
                            break;
                        case -2:
                            llBottomBt.setVisibility(View.GONE);
                            break;
                        case 1:
                            tvStatus1.setText("取消订单");
                            tvStatus1.setVisibility(View.VISIBLE);
                            tvStatus2.setText("立即付款");
                            tvStatus2.setVisibility(View.VISIBLE);
                            break;
                        case 2:
                            llBottomBt.setVisibility(View.GONE);
                            break;
                        case 3:
                            tvStatus1.setVisibility(View.INVISIBLE);
                            tvStatus2.setText("提醒发货");
                            tvStatus2.setVisibility(View.VISIBLE);
                            break;
                        case 4:
                            tvStatus1.setVisibility(View.INVISIBLE);
                            tvStatus2.setText("确认收货");
                            tvStatus2.setVisibility(View.VISIBLE);
                            break;
                        case 5:
                            tvStatus1.setVisibility(View.INVISIBLE);
                            tvStatus2.setText("立即评价");
                            tvStatus2.setVisibility(View.VISIBLE);
//                            tvStatus2.setVisibility(View.GONE);
//                            llBottomBt.setVisibility(View.GONE);
                            break;
                        case 6:
                            tvStatus1.setVisibility(View.INVISIBLE);
                            tvStatus1.setText("删除订单");
                            tvStatus2.setText("删除订单");
                            tvStatus2.setVisibility(View.VISIBLE);
                            tvStatus2.setBackgroundResource(R.drawable.delete_rectangle_shap_bg);
                                    tvStatus2.setTextColor(getResources().getColor(R.color.common_text_3));
                            break;
                    }

                    tvPrice.setText("￥" + DisplayUtil.double2String(orderBean.getTotal_money()));
                    tvCoupon.setText("￥" + DisplayUtil.double2String(orderBean.getCoupon_free_money()));
                    tvTotalMoney.setText("￥" + DisplayUtil.double2String(orderBean.getPay_money()));
                    if(orderBean.getPayment_type() == 5 || orderBean.getPayment_type() == 6){
                        ivRight.setVisibility(View.VISIBLE);
                    }else {
                        ivRight.setVisibility(View.GONE);
                    }
                }
            }
        });

    }





    private void remindOrder(int id ,final int status){
        //状态：-2已关闭 -1已驳回 1待付款 2待审核 3待发货 4待收货 5待评价 6已完成 ,
        String url ="";
        switch (status){
            case -2:
                break;
            case -1:
                break;
            case 1:
                url = API.ORDERS_DETIAL+id+"/pay?"+"&access_token="+ UserInfoUtil.getInfoToken(getApplicationContext());
                break;
            case 2:
                break;
            case 3:
                url = API.ORDERS_DETIAL+id+"/remind/delivery?"+"&access_token="+ UserInfoUtil.getInfoToken(this);
                break;
            case 4:
                url = API.ORDERS_DETIAL+id+"/receipt?"+"&access_token="+ UserInfoUtil.getInfoToken(this);
                break;
            case 5:
                break;
            case 6:
                url = API.ORDERS_DETIAL+id+"/delete?"+"&access_token="+ UserInfoUtil.getInfoToken(this);
                break;
            case 7:
                url = API.ORDERS_DETIAL+id+"/cancel?"+"&access_token="+ UserInfoUtil.getInfoToken(this);
                break;
        }


        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        if(status == 1){
          int payment_type = orderBean.getPayment_type();
            switch (payment_type){
                case 1: //ali
                    TypeToken<AliPayBeen> typeToken = new TypeToken<AliPayBeen>() {
                    };
                    OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<AliPayBeen>(typeToken) {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(AliPayBeen response, int id) {
                            if(response.getErr_code() == 0){
                                doZFBzf( response.getAlipay());
                            }else {
                                showToast(response.getErr_msg());
                            }
                        }
                    });
                    break;
                case 2://wx
                    TypeToken<WeiChatPayBeen> typeoken = new TypeToken<WeiChatPayBeen>() {
                    };
                    OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<WeiChatPayBeen>(typeoken) {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(WeiChatPayBeen response, int id) {
                            if(response.getErr_code() == 0){
                                wxPay(response.getWechat());
                            }else {
                                showToast(response.getErr_msg());
                            }
                        }
                    });
                    break;
                case 3://
                    TypeToken<UPPayBeen> typoken = new TypeToken<UPPayBeen>() {
                    };
                    OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<UPPayBeen>(typoken) {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(UPPayBeen response, int id) {
                            if(response.getErr_code() == 0){
                                dpUPPay(response.getUnionpay());
                            }else {
                                showToast(response.getErr_msg());
                            }
                        }
                    });
                    break;
            }
        }else {
            TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>(){};
            OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(ModelBeen response, int id) {
                    if(response.err_code == 0){
                        showToast(response.err_msg);
                        if(status != 1){
                            finish();
                        }
                    }else {
                        showToast(response.err_msg);
                    }
                }
            });
        }

    }


    private void doZFBzf(final String orderSN) {

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(
                        OrderDetailActivity.this);
                final Map<String, String> result = alipay
                        .payV2(orderSN, true);
                Log.i("msp", result.toString());
               runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showToast("result: "+result.toString());
                    }
                });
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void wxPay(WeiChatPayBeen.WechatBean wXpayResult){
        PayReq request = new PayReq();
        request.appId = wXpayResult.getAppid();
        request.partnerId = wXpayResult.getPartnerid();
        request.prepayId = wXpayResult.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wXpayResult.getNoncestr();
        request.timeStamp = wXpayResult.getTimestamp();
        request.sign = wXpayResult.getSign();
        iwxapi.registerApp(Constants.APP_ID);
        iwxapi.sendReq(request);
    }

    private void dpUPPay(String tn){
        UPPayAssistEx.startPay (this, null, null, tn, "01");
    }


}
